/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-09 13:42:01
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-28 11:14:54
 * @FilePath: \gogamewebserver\goGameWebServer\internal\common\config\configHelper.go
 * @Description: 配置处理
 */
package config

import (
	"fmt"
	"strings"

	"github.com/gogf/gf/v2/os/gfile"
	"github.com/spf13/viper"
)

func LoadConfig() *ServerOptions {
	// 获取程序运行目录
	appRunPath := gfile.SelfDir()
	yamlConfig := viper.GetViper()
	yamlConfig.AddConfigPath(appRunPath + "/res/configs/")
	yamlConfig.SetConfigName("default.yaml")
	yamlConfig.SetConfigType("yaml")
	if err := yamlConfig.ReadInConfig(); err != nil {
		panic(err)
	}
	po := NewOptions()
	if err := yamlConfig.Unmarshal(po); err != nil {
		panic(err)
	}
	return po
}

func LoadPlatformConfigs() *PlatformOptions {
	appRunPath := gfile.SelfDir()
	yamlConfig := viper.GetViper()
	yamlConfig.AddConfigPath(appRunPath + "/res/configs/")
	yamlConfig.SetConfigName("platform.yaml")
	yamlConfig.SetConfigType("yaml")
	if err := yamlConfig.ReadInConfig(); err != nil {
		panic(err)
	}
	po := NewPlatformOptions()
	if err := yamlConfig.Unmarshal(po); err != nil {
		panic(err)
	}
	return po
}

// LoadConfigFromEnv 从环境变量中读取配置并覆盖现有配置
func LoadConfigFromEnv(po *ServerOptions) {
	fmt.Println("=== 开始从环境变量加载配置 ===")

	// 使用 Viper 读取环境变量
	envViper := viper.New()
	envViper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	envViper.AutomaticEnv()

	// 绑定所有 ServerOptions 字段的环境变量
	// 服务器基础配置
	envViper.BindEnv("serverkey", "SERVERKEY")
	envViper.BindEnv("servername", "SERVERNAME")
	envViper.BindEnv("serverid", "SERVERID")
	envViper.BindEnv("serverport", "SERVERPORT")
	envViper.BindEnv("checksign", "CHECKSIGN")
	envViper.BindEnv("swagger", "SWAGGER")
	envViper.BindEnv("swaggeraccount", "SWAGGERACCOUNT")
	envViper.BindEnv("swaggerpassword", "SWAGGERPASSWORD")

	// Redis 配置
	envViper.BindEnv("redisoptions.host", "REDISOPTIONS_HOST")
	envViper.BindEnv("redisoptions.port", "REDISOPTIONS_PORT")
	envViper.BindEnv("redisoptions.pass", "REDISOPTIONS_PASS")
	envViper.BindEnv("redisoptions.db", "REDISOPTIONS_DB")

	// 日志配置
	envViper.BindEnv("logoptions.loglevel", "LOGOPTIONS_LOGLEVEL")
	envViper.BindEnv("logoptions.logpath", "LOGOPTIONS_LOGPATH")
	envViper.BindEnv("logoptions.logfilename", "LOGOPTIONS_LOGFILENAME")

	// 数据库配置 (支持多个数据库配置，索引从0开始)
	// 示例: DATABASEOPTIONS_0_HOST, DATABASEOPTIONS_0_PORT, DATABASEOPTIONS_0_NAME 等
	// 由于数据库配置是数组，这里仅做基础绑定，实际使用时需要根据具体需求调整
	for i := 0; i < 10; i++ { // 支持最多10个数据库配置
		prefix := fmt.Sprintf("databaseoptions.%d", i)
		envPrefix := fmt.Sprintf("DATABASEOPTIONS_%d", i)

		envViper.BindEnv(prefix+".host", envPrefix+"_HOST")
		envViper.BindEnv(prefix+".port", envPrefix+"_PORT")
		envViper.BindEnv(prefix+".user", envPrefix+"_USER")
		envViper.BindEnv(prefix+".pass", envPrefix+"_PASS")
		envViper.BindEnv(prefix+".name", envPrefix+"_NAME")
		envViper.BindEnv(prefix+".type", envPrefix+"_TYPE")
		envViper.BindEnv(prefix+".role", envPrefix+"_ROLE")
		envViper.BindEnv(prefix+".debug", envPrefix+"_DEBUG")
		envViper.BindEnv(prefix+".charset", envPrefix+"_CHARSET")
		envViper.BindEnv(prefix+".dryrun", envPrefix+"_DRYRUN")
		envViper.BindEnv(prefix+".maxidle", envPrefix+"_MAXIDLE")
		envViper.BindEnv(prefix+".maxopen", envPrefix+"_MAXOPEN")
		envViper.BindEnv(prefix+".maxlifetime", envPrefix+"_MAXLIFETIME")
		envViper.BindEnv(prefix+".groupname", envPrefix+"_GROUPNAME")
		envViper.BindEnv(prefix+".loadentity", envPrefix+"_LOADENTITY")
	}

	// 调试：检查部分环境变量是否被读取
	if envViper.IsSet("serverport") {
		fmt.Printf("✓ 读取环境变量 SERVERPORT: %v\n", envViper.Get("serverport"))
	}
	if envViper.IsSet("servername") {
		fmt.Printf("✓ 读取环境变量 SERVERNAME: %v\n", envViper.Get("servername"))
	}
	if envViper.IsSet("redisoptions.host") {
		fmt.Printf("✓ 读取环境变量 REDISOPTIONS_HOST: %v\n", envViper.Get("redisoptions.host"))
	}
	if envViper.IsSet("logoptions.loglevel") {
		fmt.Printf("✓ 读取环境变量 LOGOPTIONS_LOGLEVEL: %v\n", envViper.Get("logoptions.loglevel"))
	}

	// Unmarshal to override with environment variables
	if err := envViper.Unmarshal(po); err != nil {
		fmt.Printf("❌ Viper Unmarshal 失败: %v\n", err)
	}

	fmt.Println("=== 环境变量加载完成 ===")
	fmt.Printf("最终配置: ServerPort=%d, ServerName=%s, ServerID=%d, CheckSign=%v\n, ServerKey=%s",
		po.ServerPort, po.ServerName, po.ServerID, po.CheckSign, po.ServerKey)
	fmt.Printf("Redis配置: Host=%s, Port=%d, DB=%d\n",
		po.RedisOptions.Host, po.RedisOptions.Port, po.RedisOptions.DB)
	fmt.Printf("日志配置: Level=%s, Path=%s\n",
		po.LogOptions.LogLevel, po.LogOptions.LogPath)
}

var AppOptions *ServerOptions
